using System;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net.Http.Headers;

namespace GameOverlayWPF
{
    /// <summary>
    /// 版本更新服务类
    /// </summary>
    public class VersionUpdateService
    {
        private const string API_BASE_URL = "https://maqt.top";
        private const int CURRENT_VERSION_CODE = 400; // 当前应用版本代码
        private const int MAX_RETRY_COUNT = 2; // 最大重试次数
        
        private static readonly HttpClient _httpClient = new HttpClient(new SocketsHttpHandler
        {
            PooledConnectionLifetime = TimeSpan.FromMinutes(2), // 定期刷新连接，避免DNS缓存问题
            ConnectTimeout = TimeSpan.FromSeconds(5)
        })
        {
            Timeout = TimeSpan.FromSeconds(10)
        };

        /// <summary>
        /// 检查是否有新版本（带重试机制）
        /// </summary>
        /// <returns>如果有新版本，返回版本信息；否则返回null</returns>
        public static async Task<VersionInfo?> CheckForUpdates()
        {   
            for (int attempt = 0; attempt <= MAX_RETRY_COUNT; attempt++)
            {
                try
                {
                    var url = $"{API_BASE_URL}/api/maqt-beta/version/latest?current_version_code={CURRENT_VERSION_CODE}";
                    Debug.WriteLine($"检查更新 (尝试 {attempt + 1}/{MAX_RETRY_COUNT + 1}): {url}");
                    
                    var response = await _httpClient.GetStringAsync(url);
                    Debug.WriteLine($"更新响应: {response}");
                    
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    
                    var result = JsonSerializer.Deserialize<VersionResponse>(response, options);
                    
                    if (result != null && result.Success && result.HasUpdate)
                    {
                        return result.Version;
                    }
                    
                    return null;
                }
                catch (HttpRequestException ex)
                {
                    Debug.WriteLine($"检查更新网络错误 (尝试 {attempt + 1}): {ex.Message}");
                    if (attempt == MAX_RETRY_COUNT)
                    {
                        Debug.WriteLine("已达到最大重试次数，放弃检查更新");
                        return null;
                    }
                    // 等待后重试，使用指数退避
                    await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
                }
                catch (TaskCanceledException ex)
                {
                    Debug.WriteLine($"检查更新超时 (尝试 {attempt + 1}): {ex.Message}");
                    if (attempt == MAX_RETRY_COUNT)
                    {
                        return null;
                    }
                    await Task.Delay(TimeSpan.FromSeconds(1));
                }
                catch (JsonException ex)
                {
                    Debug.WriteLine($"检查更新JSON解析失败: {ex.Message}");
                    // JSON解析错误不重试
                    return null;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"检查更新失败: {ex.Message}");
                    return null;
                }
            }
            
            return null;
        }

        /// <summary>
        /// 记录用户点击更新按钮
        /// </summary>
        /// <param name="versionId">版本ID</param>
        public static async Task RecordUpdateClick(int versionId)
        {
            try
            {
                var url = $"{API_BASE_URL}/api/maqt-beta/version/{versionId}/click";
                await _httpClient.PostAsync(url, null);
                Debug.WriteLine($"更新点击已记录: {versionId}");
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"记录点击失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 打开下载链接
        /// </summary>
        /// <param name="downloadUrl">下载链接</param>
        public static void OpenDownloadUrl(string downloadUrl)
        {
            try
            {
                Process.Start(new ProcessStartInfo
                {
                    FileName = downloadUrl,
                    UseShellExecute = true
                });
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"打开下载链接失败: {ex.Message}");
            }
        }
    }

    /// <summary>
    /// API响应模型
    /// </summary>
    public class VersionResponse
    {
        [JsonPropertyName("success")]
        public bool Success { get; set; }

        [JsonPropertyName("has_update")]
        public bool HasUpdate { get; set; }

        [JsonPropertyName("version")]
        public VersionInfo? Version { get; set; }

        [JsonPropertyName("message")]
        public string? Message { get; set; }
    }

    /// <summary>
    /// 版本信息模型
    /// </summary>
    public class VersionInfo
    {
        [JsonPropertyName("id")]
        public int Id { get; set; }

        [JsonPropertyName("version_name")]
        public string VersionName { get; set; } = string.Empty;

        [JsonPropertyName("version_code")]
        public int VersionCode { get; set; }

        [JsonPropertyName("update_title")]
        public string UpdateTitle { get; set; } = string.Empty;

        [JsonPropertyName("update_content")]
        public string UpdateContent { get; set; } = string.Empty;

        [JsonPropertyName("download_url")]
        public string DownloadUrl { get; set; } = string.Empty;

        [JsonPropertyName("is_force_update")]
        public bool IsForceUpdate { get; set; }

        [JsonPropertyName("release_date")]
        public DateTime ReleaseDate { get; set; }
    }
}
